package com.mercury.ec.module.air.controller.admin.order;

import com.mercury.ec.framework.air.core.client.dto.order.create.AirOrderCreateReqDTO;
import com.mercury.ec.framework.air.core.client.dto.order.create.AirOrderCreateRespDTO;
import com.mercury.ec.framework.common.exception.ServiceException;
import com.mercury.ec.framework.common.pojo.CommonResult;
import com.mercury.ec.framework.common.pojo.PageResult;
import com.mercury.ec.framework.common.util.object.BeanUtils;
import com.mercury.ec.framework.web.core.util.WebFrameworkUtils;
import com.mercury.ec.module.air.controller.admin.order.vo.order.*;
import com.mercury.ec.module.air.enums.AirOrderTypeEnum;
import com.mercury.ec.module.air.service.api.AirApiService;
import com.mercury.ec.module.air.service.order.AirOrderService;
import com.mercury.ec.module.basic.enums.BasicPassengerTypeEnum;
import com.mercury.ec.module.system.dal.dataobject.user.AdminUserDO;
import com.mercury.ec.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

import static com.mercury.ec.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.mercury.ec.framework.common.pojo.CommonResult.success;
import static com.mercury.ec.module.air.enums.ErrorCodeConstants.*;

@Tag(name = "管理后台 - 机票订单")
@RestController
@RequestMapping("/air/order")
@Validated
public class AirOrderController {

    @Resource
    private AirOrderService airOrderService;
    @Resource
    private AdminUserService adminUserService;
    @Resource
    private AirApiService airApiService;

    @PostMapping("/create")
    @Operation(summary = "创建机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:create')")
    public CommonResult<Long> createOrder(@Valid @RequestBody AirOrderCreateReqVO createReqVO) {
        if (createReqVO.getOccupySeat()) {
            // 接口下单
            AirOrderCreateRespDTO airOrderCreateRespDTO = airApiService.createOrder(BeanUtils.toBean(createReqVO, AirOrderCreateReqDTO.class));
            createReqVO.setBookChannelId(airOrderCreateRespDTO.getBookChannelId());
            createReqVO.setPnr(airOrderCreateRespDTO.getOrderNo());
        }
        return success(airOrderService.createOrder(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:update')")
    public CommonResult<Boolean> updateOrder(@Valid @RequestBody AirOrderUpdateReqVO updateReqVO) {
        return success(airOrderService.updateOrder(updateReqVO));
    }

    @PutMapping("/super-update")
    @Operation(summary = "超级更新机票订单", description = "用于出票后的更新，涉及自动调账等一系列操作")
    @PreAuthorize("@ss.hasPermission('air:order:super-update')")
    public CommonResult<Boolean> superUpdateOrder(@Valid @RequestBody AirOrderSuperUpdateReqVO superUpdateReqVO) {
        return success(airOrderService.superUpdateOrder(superUpdateReqVO));
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除机票订单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('air:order:delete')")
    public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
        airOrderService.deleteOrder(id);
        return success(true);
    }

    @PutMapping("/confirm")
    @Operation(summary = "确认机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:confirm')")
    public CommonResult<Boolean> confirmOrder(@Valid @RequestBody AirOrderConfirmReqVO confirmReqVO) {
        return success(airOrderService.confirmOrder(confirmReqVO));
    }

//    @PutMapping("/pay")
//    @Operation(summary = "支付机票订单")
//    @PreAuthorize("@ss.hasPermission('air:order:pay')")
//    public CommonResult<AirOrderPayRespVO> payOrder(@Valid @RequestBody AirOrderPayReqVO payReqVO) {
//        return success(airOrderService.payOrder(payReqVO));
//    }

    @PutMapping("/audit")
    @Operation(summary = "审核机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:audit')")
    public CommonResult<Boolean> auditOrder(@Valid @RequestBody AirOrderAuditReqVO auditReqVO) {
        return success(airOrderService.auditOrder(auditReqVO));
    }

    @PutMapping("/issue")
    @Operation(summary = "机票订单出票", description = "机票订单半自动出票")
    @PreAuthorize("@ss.hasPermission('air:order:issue')")
    public CommonResult<Boolean> issueOrder(@Valid @RequestBody AirOrderIssueReqVO issueReqVO) {
        // 校验锁单
        AdminUserDO user = adminUserService.getUser(WebFrameworkUtils.getLoginUserId());
        AirOrderRespVO order = airOrderService.getOrder(issueReqVO.getId());
        if (!order.getLocked()) {
            throw exception(AIR_ORDER_NOT_LOCKER_NOT_ALLOW_ISSUE);
        } else {
            if (!Objects.equals(order.getLockUserId(), user.getId())) {
                AdminUserDO lockUser = adminUserService.getUser(order.getLockUserId());
                throw exception(AIR_ORDER_NOT_LOCKER_NOT_ALLOW_UNLOCK, lockUser.getNickname());
            }
        }
        // 非销售单不允许自动出票
        if (!AirOrderTypeEnum.isSale(order.getType())) {
            throw exception(AIR_ORDER_NOT_SUPPORT_TYPE_NOT_ALLOW_ISSUE);
        }
        // 非成人订单不允许自动出票
        long adultPassengerCount = order.getPassengers().stream().filter(p -> BasicPassengerTypeEnum.isAdult(p.getType())).count();
        if (order.getPassengers().size() != adultPassengerCount) {
            throw exception(AIR_ORDER_NOT_ADULT_NOT_ALLOW_ISSUE);
        }
        try {
            airOrderService.issueOrder(issueReqVO);
        } catch (ServiceException e) {
            throw e;
        } finally {
            AirOrderLockReqVO airOrderLockReqVO = new AirOrderLockReqVO();
            airOrderLockReqVO.setId(issueReqVO.getId());
            airOrderService.unlockOrder(airOrderLockReqVO);
        }
        return success(true);
    }

    @PutMapping("/refuse-issue")
    @Operation(summary = "机票订单拒绝出票", description = "机票订单拒绝出票")
    @PreAuthorize("@ss.hasPermission('air:order:refuse-issue')")
    public CommonResult<Boolean> refuseIssueOrder(@Valid @RequestBody AirOrderRefuseIssueReqVO refuseIssueReqVO) {
        airOrderService.refuseIssueOrder(refuseIssueReqVO);
        return success(true);
    }

    @PutMapping("/issued")
    @Operation(summary = "机票订单已出票", description = "用于一键完成订单到已客票状态")
    @PreAuthorize("@ss.hasPermission('air:order:issued')")
    public CommonResult<Boolean> issuedOrder(@Valid @RequestBody AirOrderIssuedReqVO issuedReqVO) {
        // 校验锁单
        AdminUserDO user = adminUserService.getUser(WebFrameworkUtils.getLoginUserId());
        AirOrderRespVO order = airOrderService.getOrder(issuedReqVO.getId());
        if (!order.getLocked()) {
            throw exception(AIR_ORDER_NOT_LOCKER_NOT_ALLOW_ISSUED);
        } else {
            if (!Objects.equals(order.getLockUserId(), user.getId())) {
                AdminUserDO lockUser = adminUserService.getUser(order.getLockUserId());
                throw exception(AIR_ORDER_NOT_LOCKER_NOT_ALLOW_UNLOCK, lockUser.getNickname());
            }
        }
        return success(airOrderService.issuedOrder(issuedReqVO));
    }

    @PostMapping("/apply-change")
    @Operation(summary = "机票订单申请改签", description = "基于销售单或者改签单进行改签申请，生成新的改签单")
    @PreAuthorize("@ss.hasPermission('air:order:apply-change')")
    public CommonResult<Long> applyChangeOrder(@Valid @RequestBody AirOrderApplyChangeReqVO applyChangeReqVO) {
        return success(airOrderService.applyChangeOrder(applyChangeReqVO));
    }

    @PostMapping("/apply-return")
    @Operation(summary = "机票订单申请退票", description = "基于销售单或者改签单进行退票申请，生成新的退票单")
    @PreAuthorize("@ss.hasPermission('air:order:apply-return')")
    public CommonResult<Long> applyReturnOrder(@Valid @RequestBody AirOrderApplyReturnReqVO applyReturnReqVO) {
        return success(airOrderService.applyReturnOrder(applyReturnReqVO));
    }

    @PutMapping("/cancel")
    @Operation(summary = "取消机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:cancel')")
    public CommonResult<Boolean> cancelOrder(@Valid @RequestBody AirOrderCancelReqVO cancelReqVO) {
        return success(airOrderService.cancelOrder(cancelReqVO));
    }

    @PutMapping("/lock")
    @Operation(summary = "锁定机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:lock')")
    public CommonResult<Boolean> lockOrder(@Valid @RequestBody AirOrderLockReqVO lockReqVO) {
        return success(airOrderService.lockOrder(lockReqVO));
    }

    @PutMapping("/unlock")
    @Operation(summary = "解锁机票订单")
    @PreAuthorize("@ss.hasPermission('air:order:unlock')")
    public CommonResult<Boolean> unlockOrder(@Valid @RequestBody AirOrderLockReqVO lockReqVO) {
        return success(airOrderService.unlockOrder(lockReqVO));
    }

    @GetMapping("/get")
    @Operation(summary = "获得机票订单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('air:order:query')")
    public CommonResult<AirOrderRespVO> getOrder(@RequestParam("id") Long id) {
        return success(airOrderService.getOrder(id));
    }

    @GetMapping("/get-by-no")
    @Operation(summary = "根据订单号获得机票订单")
    @Parameter(name = "no", description = "订单号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('air:order:query')")
    public CommonResult<AirOrderRespVO> getOrderByNo(@RequestParam("no") String no) {
        return success(airOrderService.getOrderByNo(no));
    }

    @GetMapping("/page")
    @Operation(summary = "获得机票订单分页")
    @PreAuthorize("@ss.hasPermission('air:order:query')")
    public CommonResult<PageResult<AirOrderRespVO>> getOrderPage(@Valid AirOrderPageReqVO pageReqVO) {
        return success(airOrderService.getOrderPage(pageReqVO));
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出机票订单 Excel")
//    @PreAuthorize("@ss.hasPermission('air:order:export')")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportOrderExcel(@Valid AirOrderPageReqVO pageReqVO,
//              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<AirOrderRespVO> list = airOrderService.getOrderPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "机票订单.xls", "数据", AirOrderRespVO.class,
//                        BeanUtils.toBean(list, AirOrderRespVO.class));
//    }

}
